<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { Sunny, Moon } from '@element-plus/icons-vue'

import { useTheme } from '@/hooks/web/useTheme'
import { useAppStore } from '@/store/modules/app'

const { switchDark } = useTheme()
const { isDark } = storeToRefs(useAppStore())

/**
 * 改变视图
 * @param event MouseEvent
 */
const updateView = (event: MouseEvent) => {
  // 在不支持的浏览器里不做动画
  if (!document.startViewTransition) {
    switchDark()
    return
  }
  const transition = document.startViewTransition(() => {
    switchDark()
  })
  // @ts-ignore
  // 在 transition.ready 的 Promise 完成后，执行自定义动画
  transition.ready.then(() => {
    // 由于我们要从鼠标点击的位置开始做动画，所以我们需要先获取到鼠标的位置
    const { clientX, clientY } = event

    // 计算半径，以鼠标点击的位置为圆心，到四个角的距离中最大的那个作为半径
    const raduis = Math.hypot(Math.max(clientX, innerWidth - clientX), Math.max(clientY, innerHeight - clientY))

    const clipPath = [`circle(0% at ${clientX}px ${clientY}px)`, `circle(${raduis}px at ${clientX}px ${clientY}px)`]

    // const dark = document.documentElement.classList.contains('dark')
    document.documentElement.animate(
      {
        clipPath: isDark.value ? clipPath.reverse() : clipPath
      },
      {
        duration: 500,
        easing: 'ease-in-out',
        pseudoElement: isDark.value ? '::view-transition-old(root)' : '::view-transition-new(root)'
      }
    )
  })
}
</script>

<template>
  <div id="switchRef" class="dark-mode" @click="updateView">
    <el-switch v-model="isDark" inline-prompt :active-icon="Sunny" :inactive-icon="Moon" />
  </div>
</template>
